package com.ctbri.containerindepth;

import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.SortedSet;

public class Ex10<E> implements SortedSet<E> {
	public Ex10() {
		elements = new LinkedList<E>();
	}
	
	public Ex10(List<E> list) {
		elements = list;
	}

	private List<E> elements;

	@Override
	public int size() {
		return elements.size();
	}

	@Override
	public boolean isEmpty() {
		return elements.isEmpty();
	}

	@Override
	public boolean contains(Object o) {
		return elements.contains(o);
	}

	@Override
	public Iterator<E> iterator() {
		return elements.iterator();
	}

	@Override
	public Object[] toArray() {
		return elements.toArray();
	}

	@Override
	public <T> T[] toArray(T[] a) {
		return elements.toArray(a);
	}

	@SuppressWarnings("unchecked")
	@Override
	public boolean add(E e) {
		int index = Collections.binarySearch((List<Comparable<E>>)elements, e);
		if(index < 0) {
			index = -(index + 1);
			if(index == elements.size())
				elements.add(e);
			else
				elements.add(index, e);
			return true;
		}
		return false;
	}

	@Override
	public boolean remove(Object o) {
		return elements.remove(o);
	}

	@Override
	public boolean containsAll(Collection<?> c) {
		return elements.containsAll(c);
	}

	@Override
	public boolean addAll(Collection<? extends E> c) {
		boolean result = false;
		for(E item : c)
			result |= add(item);
		return result;
	}

	@Override
	public boolean retainAll(Collection<?> c) {
		return elements.retainAll(c);
	}

	@Override
	public boolean removeAll(Collection<?> c) {
		return elements.removeAll(c);
	}

	@Override
	public void clear() {
		elements.clear();
	}

	@Override
	public Comparator<? super E> comparator() {
		return null;
	}

	@Override
	public SortedSet<E> subSet(E fromElement, E toElement) {
		int fromIndex = elements.indexOf(fromElement);
		int toIndex = elements.indexOf(toElement);
		return new Ex10<E>(elements.subList(fromIndex, toIndex));
	}

	@Override
	public SortedSet<E> headSet(E toElement) {
		int toIndex = elements.indexOf(toElement);
		return new Ex10<E>(elements.subList(0, toIndex));
	}

	@Override
	public SortedSet<E> tailSet(E fromElement) {
		int fromIndex = elements.indexOf(fromElement);
		return new Ex10<E>(elements.subList(fromIndex, elements.size()));
	}

	@Override
	public E first() {
		return elements.get(0);
	}

	@Override
	public E last() {
		return elements.get(elements.size() - 1);
	}
	
	public static void main(String[] args) {

	}


}
